package com.jh3502.helper.function.batch.mytask;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.jh3502.helper.R;
import com.jh3502.helper.base.BaseFragment;
import com.jh3502.helper.function.batch.batchnew.BatchNewActivity;
import com.jh3502.helper.function.person.personlist.PersonListBean;
import com.jh3502.helper.function.person.personlist.PersonListFragment;
import com.jh3502.helper.utils.Constant;
import com.jh3502.helper.utils.ExcelUtil;
import com.jh3502.helper.utils.SpHelper;
import com.jh3502.helper.utils.Utils;
import com.jh3502.helper.utils.bluetooth.ConnectEvent;
import com.jh3502.helper.view.ActionSheetDialog;
import com.jh3502.helper.view.MyRecyclerView;
import com.vise.xsnow.event.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author harisucici
 */
public class MyTaskFragment extends BaseFragment implements MyTaskPresenter.MyTaskView {
    @Nullable
    @BindView(R.id.fragment_home1_recycler)
    MyRecyclerView fragmentHome1Recycler;
    Unbinder unbinder;
    @BindView(R.id.my_task_blue_ruler)
    ImageView myTaskBlueRuler;
    private MyTaskAdapter mAdapter;
    @NonNull
    private ArrayList<Map<String, Object>> msg = new ArrayList<>();
    private String batno;
    @NonNull
    private String[] scanType = {"全部", "已完成", "未完成"};

    private MyTaskPresenter batchListPresenter;

    @Override
    protected int setViewId() {
        return R.layout.fragment_my_task;
    }

    @Override
    protected void initView() {

//        titlebar.setBackgroundResource(R.drawable.shape_title);
//        titlebar.getCenterTextView().setText("量体任务单");
//        titlebar.setListener(new CommonTitleBar.OnTitleBarListener() {
//            @Override
//            public void onClicked(View v, int action, String extra) {
//                if (action == CommonTitleBar.ACTION_LEFT_BUTTON) {
////                    onBackPressed();
//                } else if (action == CommonTitleBar.ACTION_RIGHT_TEXT) {
//                    ActionSheetDialog actionSheetDialogType = new ActionSheetDialog(mContext);
//                    actionSheetDialogType.builder().setCancelable(false).setCanceledOnTouchOutside(true);
//                    ArrayList<Map<String, Object>> batchListTemp = SpHelper.getInstance().getBatchList();
//                    ArrayList<Map<String, Object>> batchList = new ArrayList<>(2);
//                    for (int i = 0; i < scanType.length; i++) {
//                        String title = scanType[i];
//                        int finalI = i;
//                        actionSheetDialogType.addSheetItem(title, R.color.green, () -> {
//                            switch (finalI) {
//                                case 0:
//                                    msg.clear();
//                                    msg.addAll(batchListTemp);
//                                    mAdapter.notifyDataSetChanged();
//                                    break;
//                                case 1:
//                                    msg.clear();
//                                    for (Map<String, Object> map : batchListTemp) {
//                                        if (map.get("status").equals(Constant.BATCH_FINAL)) {
//                                            batchList.add(map);
//                                        }
//                                    }
//                                    msg.addAll(batchList);
//                                    mAdapter.notifyDataSetChanged();
//                                    break;
//                                case 2:
//                                    msg.clear();
//                                    for (Map<String, Object> map : batchListTemp) {
//                                        if (map.get("status").equals(Constant.BATCH_UN_FINAL)) {
//                                            batchList.add(map);
//                                        }
//                                    }
//                                    msg.addAll(batchList);
//                                    mAdapter.notifyDataSetChanged();
//                                    break;
//                                default:
//                                    break;
//                            }
//                        });
//                    }
//                    actionSheetDialogType.show();
//                }
//            }
//        });


        batchListPresenter = new MyTaskPresenter();
        batchListPresenter.setMyTaskView(this);
        batchListPresenter.toListall(SpHelper.getInstance().getUserName());
        mAdapter = new MyTaskAdapter(mContext, msg);
        fragmentHome1Recycler.setAdapter(mAdapter);

        mAdapter.setButtonSetOnclickConfig(position -> {
            showShortToast("Config");
            Utils.getInstance().startActivity(mActivity, PersonListFragment.class);
        });

        mAdapter.setButtonSetOnclickDelete(position -> {
            showShortToast("Delete");
//            Utils.getInstance().startActivity(mActivity, PersonListFragment.class);
        });
        mAdapter.setButtonSetOnclickView(position -> {
            showShortToast("View");
//            Utils.getInstance().startActivity(mActivity, PersonListFragment.class);
        });

        mAdapter.setButtonSetOnclickTest(position -> {
            showShortToast("Test");
//            Utils.getInstance().startActivity(mActivity, PersonListFragment.class);
        });


        mAdapter.setOnItemClickListener(s -> {

            if (Utils.getInstance().isFastDoubleClick()) {
                return;
            }

            if (msg.get(Integer.parseInt(s)).get("status").equals(Constant.BATCH_FINAL)) {
                showShortToast("不允许已完成任务作为首选");
                return;
            }
            batno = (String) msg.get(Integer.parseInt(s)).get("batno");
            if ("".equals(SpHelper.getInstance().getBatAct())) {//没有活动量体任务
                ActionSheetDialog actionSheetDialogType = new ActionSheetDialog(mContext);
                actionSheetDialogType.builder().setCancelable(false).setCanceledOnTouchOutside(true);
                actionSheetDialogType.setTitle("是否将当前量体任务置为活动量体任务");
                actionSheetDialogType.addSheetItem("确认", R.color.green, () -> {
                    String batInfo = new Gson().toJson(msg.get(Integer.parseInt(s)));
                    SpHelper.getInstance().setBatAct(batInfo);
                    mAdapter.notifyDataSetChanged();//刷新列表
                    batchListPresenter.toGetoneall(batno);
                });
                actionSheetDialogType.show();
            } else {
                Map<String, Object> batInfoMap = Utils.getInstance().jso2map(SpHelper.getInstance().getBatAct());
                if (batInfoMap.get("batno").equals(batno)) {
                    Utils.getInstance().startActivity(mActivity, BatchNewActivity.class);
//                    Utils.getInstance().startActivity(this, PersonListActivity.class);
                } else {
                    ActionSheetDialog actionSheetDialogType = new ActionSheetDialog(mContext);
                    actionSheetDialogType.builder().setCancelable(false).setCanceledOnTouchOutside(true);
                    actionSheetDialogType.setTitle("是否将当前量体任务置为活动量体任务");
                    actionSheetDialogType.addSheetItem("确认", R.color.green, () -> {
                        //清空所选量体部位
                        SpHelper.getInstance().putString(Constant.CHOSEN_UPDERSS, "");
                        SpHelper.getInstance().putString(Constant.CHOSEN_DOWNDERSS, "");
                        mAdapter.notifyDataSetChanged();//刷新列表
                        String batInfo = new Gson().toJson(msg.get(Integer.parseInt(s)));
                        SpHelper.getInstance().setBatAct(batInfo);
                        batchListPresenter.toGetoneall(batno);
                    });
                    actionSheetDialogType.show();
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @NonNull Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String path = Utils.getInstance().getPath(mContext, uri);
            String[] temp = path.split("\\.");
            int i = temp.length - 1;
            if ("xls".equals(temp[i]) || "XLS".equals(temp[i])) {
                SpHelper.getInstance().setPersonList(batno, ExcelUtil.getInstance().importExcelData(path));
//                String s = SpHelper.getInstance().getString(batno);
//                List<PersonListBean> a = Utils.getInstance().map2Person(s);
//                Map<String, Object> b = Utils.getInstance().person2Map(a);
                showShortToast("导入成功");
            } else {
                showShortToast("不是有效的Excel2003文件");
            }

        }
    }


    @Override
    protected void initData() {


    }

    @Override
    protected void doOnDestroyView() {

    }

    @Override
    protected void doOnResume() {

    }

    @Override
    protected void doOnVisible() {

    }

    @Override
    protected void doOnInvisible() {

    }

    @Override
    protected void doOnSaveInstanceState() {

    }


    @Override
    public void responseError(int code, @NonNull String msg) {
        showShortToast(msg);
    }

    @Override
    public void requestFailure(Throwable t) {
        msg.clear();
        msg.addAll(SpHelper.getInstance().getBatchList());
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void getoneallSuccess(@NonNull Map<String, Object> map) {
        ArrayList<Map<String, Object>> datalist = Utils.getInstance().jsa2list((String) map.get("datalist"));
        if (datalist.isEmpty()) {//没有在线
            List<PersonListBean> s = SpHelper.getInstance().getPersonList(batno);
            if (SpHelper.getInstance().getPersonList(batno).isEmpty()) {//没有离线
                // 没有在线信息 请求导入
                ActionSheetDialog actionSheetDialogType = new ActionSheetDialog(mContext);
                actionSheetDialogType.builder().setCancelable(false).setCanceledOnTouchOutside(true);
                actionSheetDialogType.setTitle("没有人员信息,是否导入?");
                actionSheetDialogType.addSheetItem("确认", R.color.green, () -> {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("application/vnd.ms-excel");
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivityForResult(intent, Constant.GET_FILE);
                });
                actionSheetDialogType.show();
            }

        } else {
            SpHelper.getInstance().setPersonList(map);
            showShortToast("人员信息同步成功");
        }
    }

    @Override
    public void listallSuccess(String rows) {
        if (!"".equals(rows)) {
            SpHelper.getInstance().setBatchList(rows);
        }
        msg.clear();
        msg.addAll(SpHelper.getInstance().getBatchList());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void saveoneallSuccess() {
        showShortToast("数据上传成功");
    }

//    @OnCheckedChanged(R.id.my_task_blue_ruler)
//    void onCheckBoxBRCheckChange(boolean b) {
//        if(b){
//            mActivity.initBlueTooth();
//        }
//
//    }

    @Subscribe
    public void showConnectedDevice(@Nullable ConnectEvent event) {
        if (event != null) {
            if (event.isSuccess()) {
                showShortToast("E尺连接成功");
                if (event.getDeviceMirror() != null && event.getDeviceMirror().getBluetoothGatt() != null) {
                    mActivity.displayGattServices(event.getDeviceMirror().getBluetoothGatt().getServices());
                }
                mActivity.getUuid(mJh3502HelperApplication.getExtraDevice());
                myTaskBlueRuler.setBackground(ContextCompat.getDrawable(mContext,R.drawable.navibar_switch_on));

            } else {
                if (event.isDisconnected()) {
                    showShortToast("已断开连接");
                } else {
                    showShortToast("连接失败");
                }
                mJh3502HelperApplication.setExtraDevice(null);
                mActivity.clearUI();
                myTaskBlueRuler.setBackground(ContextCompat.getDrawable(mContext,R.drawable.navibar_switch_off));
            }
        }
    }

    @OnClick(R.id.my_task_blue_ruler)
    public void onMyTaskBlueRulerClicked() {
        mActivity.initBlueTooth();
    }



}
